<template>
  <view class="image-viewer" v-if="showViewer">
    <!-- 头部信息区 - 放置在图片上方 -->
    <view class="header" v-if="showControls">
      <image :src="avatar" class="avatar" mode="aspectFill"></image>
      <text class="nickname">{{ nickname }}</text>
    </view>



    <!-- 主图片区（可缩放） -->
    <view class="image-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"
      @touchcancel="handleTouchEnd">
      <image :src="imageUrl" class="main-image" mode="aspectFit" :style="{
        transform: `scale(${scale}) translate(${translateX}px, ${translateY}px)`,
        transition: 'transform 0.1s ease-out',
        touchAction: 'none',
        userSelect: 'none',
        webkitUserSelect: 'none'
      }" @load="onImageLoad"></image>
    </view>
    <!-- 文字内容区（移动到图片上方） -->
    <view class="text-container" v-if="showControls">
      <!-- 内容区 -->
      <view class="content">
        <!-- 添加隐藏的测量元素 -->
        <text class="content-measure" :style="{ visibility: 'hidden', position: 'absolute', top: 0, left: 0 }">
          {{ content }}
        </text>
        <text class="content-text" :class="{ 'expanded': isExpanded }">{{ content }}
          <template v-if="showExpandBtn">
            <text class="expand-btn" @click="openContentPopup">{{ isExpanded ? '收起' : '...展开' }}</text>
          </template>
        </text>
      </view>
    </view>

    <!-- 底部操作区 -->
    <view class="footer">
      <view class="footer-left">
         <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/close.png')" @click="closeViewer" style="width: 46rpx;height: 46rpx;"></image>
       
      </view>
      <view class="footer-right" v-if="showControls">
        <button class="action-btn" open-type="share" @click="handleShare">
          <uni-icons type="redo" size="20" color="#FFFFFF"></uni-icons>
          <text class="action-text">分享</text>
        </button>

        <view class="action-btn" @click="handleComment">
          <uni-icons type="chat" size="20" color="#FFFFFF"></uni-icons>
          <text class="action-text">{{ commentCount > 0 ? commentCount : '评论' }}</text>
        </view>
        <view class="action-btn" @click="handleLike">
          <uni-icons :type="liked ? 'heart-filled' : 'heart'" size="20"
            :color="liked ? '#F76F17' : '#FFFFFF'"></uni-icons>
          <text class="action-text" :style="liked ? 'color: #F76F17' : ''">{{ likeCount > 0 ? likeCount : '点赞' }}</text>
        </view>
      </view>
    </view>

    <!-- 内容弹窗 -->
    <uni-popup ref="contentPopup" type="bottom">
      <view class="content-popup">
        <text class="popup-content">{{ content }}</text>
        <view class="popup-close" @click="closeContentPopup">收起</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getFullImageUrl } from '../../utils/request';

export default {
  props: {
    showViewer: {
      type: Boolean,
      default: false
    },
    // 控制是否显示头部、内容和底部操作控件
    showControls: {
      type: Boolean,
      default: true
    },
    avatar: {
      type: String,
      default: ''
    },
    nickname: {
      type: String,
      default: ''
    },
    imageUrl: {
      type: String,
      default: ''
    },
    commentCount: {
      type: Number,
      default: 0
    },
    content: {
      type: String,
      default: ''
    },
    likeCount: {
      type: Number,
      default: 0
    },
    liked: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isExpanded: false,
      showExpandBtn: false,
      contentHeight: 0,
      // 缩放相关数据
      scale: 1,
      minScale: 0.5,  // 允许缩小到原始尺寸的50%
      maxScale: 4,
      translateX: 0,
      translateY: 0,
      lastDistance: 0,
      lastTranslateX: 0,
      lastTranslateY: 0,
      touchStartTime: 0,
      touchEndTime: 0,
      lastTapTime: 0, // 用于检测双击事件
      isPinching: false,
      // 保存上一次触摸位置
      lastTouchX: 0,
      lastTouchY: 0,
      // 图片原始尺寸
      imageWidth: 0,
      imageHeight: 0
    };
  },
  watch: {
    content() {
      this.checkContentHeight();
    },
    showViewer(newVal) {
      // 当打开图片查看器时重置缩放状态
      if (newVal) {
        this.resetZoom();
      }
    }
  },
  mounted() {
    this.checkContentHeight();
  },
  methods: {
    getFullImageUrl,
    closeViewer() {
      this.resetZoom();
      this.$emit('update:showViewer', false);
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    },
    handleLike() {
      this.$emit('like', !this.liked);
    },
    handleComment() {
      this.$emit('comment');
    },
    handleShare() {
      uni.share({
        title: this.content,
        imageUrl: this.imageUrl,
        success: () => {
          uni.showToast({ title: '分享成功' });
        },
        fail: () => {
          // uni.showToast({ title: '分享失败', icon: 'none' });
        }
      });
    },
    checkContentHeight() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.content-measure').boundingClientRect(res => {
          if (res && res.height) {
            // 获取实际像素高度
            const contentHeightPx = res.height

            // 计算3行高度的像素值（基于你的样式：line-height:44rpx）
            const rpxToPx = uni.getSystemInfoSync().windowWidth / 750 // 使用uni API替代window.innerWidth
            const lineHeightPx = 44 * rpxToPx
            const thresholdPx = lineHeightPx * 3 * 1.1 // 3行高度+10%余量

            console.log(`内容高度:${contentHeightPx}, 阈值:${thresholdPx}, 显示按钮:${contentHeightPx > thresholdPx}`)
            this.showExpandBtn = contentHeightPx > thresholdPx
          }
        }).exec()
      })
    },
    openContentPopup() {
      this.$refs.contentPopup.open();
    },
    closeContentPopup() {
      this.$refs.contentPopup.close();
    },
    // 图片加载完成后获取原始尺寸
    onImageLoad(e) {
      this.imageWidth = e.detail.width;
      this.imageHeight = e.detail.height;
    },
    // 重置缩放状态
    resetZoom() {
      this.scale = 1;
      this.translateX = 0;
      this.translateY = 0;
      this.lastTranslateX = 0;
      this.lastTranslateY = 0;
      this.lastDistance = 0;
      this.isPinching = false;
    },
    // 触摸开始事件
    handleTouchStart(e) {
      this.touchStartTime = new Date().getTime();
      // 保存当前的位移状态
      this.lastTranslateX = this.translateX;
      this.lastTranslateY = this.translateY;

      // 保存当前触摸位置
      if (e.touches.length === 1) {
        this.lastTouchX = e.touches[0].clientX;
        this.lastTouchY = e.touches[0].clientY;
      }

      // 双指触摸，计算初始距离
      if (e.touches.length === 2) {
        this.lastDistance = this.getDistance(e.touches[0], e.touches[1]);
        this.isPinching = true;
      }
    },
    // 触摸移动事件
    handleTouchMove(e) {
      // 阻止页面滚动
      if (e.cancelable) {
        e.preventDefault();
      }

      if (e.touches.length === 1 && !this.isPinching) {
        // 单指拖动（任何缩放状态下都允许拖动）
        const dx = e.touches[0].clientX - this.lastTouchX;
        const dy = e.touches[0].clientY - this.lastTouchY;

        // 更新位移，使用更灵敏的计算方式
        this.translateX = this.lastTranslateX + dx;
        this.translateY = this.lastTranslateY + dy;

        // 保存当前触摸位置用于下一次计算
        this.lastTouchX = e.touches[0].clientX;
        this.lastTouchY = e.touches[0].clientY;

        // 实时限制拖动范围，提高拖动体验
        this.limitTranslation();
      } else if (e.touches.length === 2) {
        // 双指缩放
        const currentDistance = this.getDistance(e.touches[0], e.touches[1]);
        const deltaDistance = currentDistance - this.lastDistance;

        // 计算缩放比例
        const deltaScale = deltaDistance * 0.003;
        let newScale = this.scale + deltaScale;

        // 限制缩放范围
        newScale = Math.max(this.minScale, Math.min(this.maxScale, newScale));

        // 直接获取容器尺寸（简化版本，更适合在触摸事件中使用）
        const windowWidth = uni.getSystemInfoSync().windowWidth;
        const windowHeight = uni.getSystemInfoSync().windowHeight;

        // 计算触摸点相对于屏幕的位置
        const touch1X = e.touches[0].clientX;
        const touch1Y = e.touches[0].clientY;
        const touch2X = e.touches[1].clientX;
        const touch2Y = e.touches[1].clientY;

        // 计算双指中心点
        const centerX = (touch1X + touch2X) / 2;
        const centerY = (touch1Y + touch2Y) / 2;

        // 计算相对于图片容器中心的偏移
        const containerCenterX = windowWidth / 2;
        const containerCenterY = windowHeight / 2;

        // 计算缩放比例
        const scaleRatio = newScale / this.scale;

        // 计算双指中心点相对于屏幕中心的偏移
        const offsetX = centerX - containerCenterX;
        const offsetY = centerY - containerCenterY;

        // 调用辅助函数计算新的位移，确保图片从双指中心点进行缩放
        this.updateScaleTranslation(offsetX, offsetY, scaleRatio);

        // 限制拖动范围
        this.limitTranslation();

        // 更新状态
        this.scale = newScale;
        this.lastDistance = currentDistance;
        this.lastTranslateX = this.translateX;
        this.lastTranslateY = this.translateY;
      }
    },
    // 触摸结束事件
    handleTouchEnd(e) {
      this.touchEndTime = new Date().getTime();

      // 点击时间太短，视为点击事件
      const touchDuration = this.touchEndTime - this.touchStartTime;
      if (touchDuration < 300 && e.touches.length === 0 && !this.isPinching) {
        const now = new Date().getTime();
        const lastTapTime = this.lastTapTime || 0;
        const tapInterval = now - lastTapTime;

        // 保存当前点击时间
        this.lastTapTime = now;

        if (tapInterval < 300 && tapInterval > 0) {
          // 双击放大图片 - 不关闭弹窗
          if (this.scale === 1) {
            this.scale = 2;
          } else {
            this.scale = 1;
          }
          this.translateX = 0;
          this.translateY = 0;
          // 清除双击标志，避免连续触发
          this.lastTapTime = 0;
          return;
        } else {
          // 延迟执行单击关闭，给双击检测留出时间
          setTimeout(() => {
            // 如果300ms内没有第二次点击，才执行关闭
            if (this.lastTapTime === now) {
              this.closeViewer();
            }
          }, 300);
        }
      }

      this.isPinching = false;
    },
    // 计算两点间距离
    getDistance(touch1, touch2) {
      const dx = touch1.clientX - touch2.clientX;
      const dy = touch1.clientY - touch2.clientY;
      return Math.sqrt(dx * dx + dy * dy);
    },
    // 计算缩放时的位移调整（适用于放大和缩小）
    updateScaleTranslation(offsetX, offsetY, scaleRatio) {
      // 核心公式：新位移 = 偏移量*(1-缩放比例) + 原位移*缩放比例
      // 这个公式确保图片从双指中心点进行缩放
      this.translateX = offsetX * (1 - scaleRatio) + this.translateX * scaleRatio;
      this.translateY = offsetY * (1 - scaleRatio) + this.translateY * scaleRatio;
    },

    // 限制位移范围，优化拖动体验
    limitTranslation() {
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const windowHeight = uni.getSystemInfoSync().windowHeight;

      // 如果有图片原始尺寸，使用图片实际比例计算，否则使用窗口尺寸
      let scaledWidth, scaledHeight;
      if (this.imageWidth && this.imageHeight) {
        // 计算图片在屏幕上的显示比例
        const imageRatio = this.imageWidth / this.imageHeight;
        const windowRatio = windowWidth / windowHeight;

        // 根据比例计算图片的显示尺寸
        if (imageRatio > windowRatio) {
          // 图片较宽
          scaledWidth = windowWidth * this.scale;
          scaledHeight = scaledWidth / imageRatio;
        } else {
          // 图片较高
          scaledHeight = windowHeight * this.scale;
          scaledWidth = scaledHeight * imageRatio;
        }
      } else {
        // 没有图片尺寸信息，回退到窗口尺寸
        scaledWidth = windowWidth * this.scale;
        scaledHeight = windowHeight * this.scale;
      }

      // 计算最大允许的位移范围，增加一些缓冲区以提高拖动灵活性
      const buffer = 50; // 增加50px的缓冲区
      const maxTranslateX = Math.max(0, (scaledWidth - windowWidth) / 2 + buffer);
      const maxTranslateY = Math.max(0, (scaledHeight - windowHeight) / 2 + buffer);

      // 限制位移，但允许一定的超范围拖动以提高体验
      this.translateX = Math.max(-maxTranslateX, Math.min(maxTranslateX, this.translateX));
      this.translateY = Math.max(-maxTranslateY, Math.min(maxTranslateY, this.translateY));
    }
  }
}
</script>

<style lang="scss" scoped>
// 颜色变量
$bg-black: #000000;
$text-white: #FFFFFF;
$text-blue: #5894F6;
$text-gray: #979797;
$text-dark-gray: #333333;
$color-orange: #F76F17;

// 尺寸变量
$border-radius: 35rpx;
$avatar-size: 46rpx;

.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: $bg-black;
  z-index: 10000;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  justify-content: flex-start;

  // 头部信息区样式
  .header {
    position: absolute;
    top: 0;
    left: calc(50% - 80rpx);

    width: 100%;
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    margin: 0 auto;
    margin-top: 60rpx;
    z-index: 20;
    // 渐变背景，确保在图片上清晰可见
    // background: linear-gradient(180deg, rgba(0, 0, 0, 0.5), transparent);

    .avatar {
      width: $avatar-size;
      height: $avatar-size;
      border-radius: 50%;
      margin-right: 15rpx;
    }

    .nickname {
      font-family: Source Han Sans CN;
      font-weight: 500;
      font-size: 26rpx;
      color: $text-white;
    }
  }

  // 主图片区样式
  .image-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    overflow: hidden;
    min-height: 0; // 防止flex项目溢出

    .main-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      transition: transform 0.1s ease-out;
      touch-action: none;
      user-select: none;
      -webkit-user-select: none;
    }
  }

  // 文字内容区样式
  .text-container {
    position: relative;
    // width: 100%;
    // padding: 20rpx;
    z-index: 50; // 提高优先级，确保显示在图片上方
    // background: rgba(0, 0, 0, 0.5);

    .content {

      font-family: Source Han Sans CN;
      font-weight: 400;
      font-size: 30rpx;
      line-height: 46rpx;
      color: $text-white;
      margin-bottom: 150rpx;
      padding: 0rpx 29rpx;
      position: relative; // 确保相对定位，为按钮绝对定位提供上下文

      .content-measure {


        white-space: pre-wrap;
      }

      .content-text {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        padding-right: 0; // 移除右侧内边距

        &.expanded {
          -webkit-line-clamp: unset;
        }
      }

      .expand-btn {
        color: $text-blue;
        font-size: 28rpx;
        margin-top: 10rpx;
        position: absolute;
        background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.9) 10%);
        right: 20rpx; // 右对齐
        bottom: 0rpx; // 底部对齐
      }
    }
  }

  // 底部操作区样式
  .footer {
    padding: 0 36rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    bottom: 38rpx;
    left: 0;
    width: 95%;
    z-index: 60;
    // background: linear-gradient(to top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0) 100%);
    padding-bottom: 20rpx;

    .footer-right {
      display: flex;
      justify-content: space-around;
      align-items: center;
      width: 70%;

      .action-btn {
        display: flex;
        align-items: center;
        margin-right: 10rpx;
        background: none;
        margin-left: 0;

        .action-text {
          font-family: Source Han Sans CN;
          font-weight: 400;
          font-size: 24rpx;
          color: $text-white;
          line-height: 41rpx;
        }
      }
    }
  }

  // 内容弹窗样式
  .content-popup {
    padding: 30rpx;
    background: $text-white;
    border-radius: #{$border-radius} #{$border-radius} 0rpx 0rpx;
    max-height: 70vh;
    overflow-y: auto;
    padding-top: 60rpx;

    .popup-content {
      font-family: Source Han Sans CN;
      font-weight: 500;
      font-size: 30rpx;
      color: #0E1C37;
      line-height: 46rpx;
    }

    .popup-close {
      width: 100%;
      height: 80rpx;
      background-color: $text-white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: Source Han Sans CN;
      font-weight: 400;
      font-size: 32rpx;
      color: $text-gray;
      margin-top: 30rpx;
    }
  }
}
</style>
